package tt.dz.egobus.servicemanager.controller.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;
import tt.dz.egobus.servicemanager.base.controller.CommonBinderController;
import tt.dz.egobus.servicemanager.bean.SpringConfigConstant;
import tt.dz.egobus.servicemanager.bean.UserSession;
import tt.dz.egobus.servicemanager.core.exception.BusinessException;
import tt.dz.egobus.servicemanager.service.WebCommonService;
import tt.dz.egobus.servicemanager.vo.JsonBack;
import tt.dz.egobus.servicemanager.vo.SystemUserVo;

import javax.servlet.http.HttpServletRequest;

import static tt.dz.egobus.servicemanager.bean.ServiceManagerCodeStatus.MANAGER_LOGIN_PASSWORD_ERROR;
import static tt.dz.egobus.servicemanager.bean.ServiceManagerCodeStatus.PARAM_ILLEGAL_ERROR;
import static tt.dz.egobus.servicemanager.bean.ServiceManagerCodeStatus.SYSTEM_CODE_ERROR;
import static tt.dz.egobus.servicemanager.core.interceptor.SessionHandlerInterceptorAdapter.ADMIN_SESSION_KEY;

/**
 * web界面公共配置
 */
@RestController
@RequestMapping("/web")
public class WebCommonController extends CommonBinderController {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebCommonController.class);

    @Autowired
    @Qualifier("webCommonServiceImpl")
    private WebCommonService service;

    @Autowired
    @Qualifier("springConfigConstant")
    private SpringConfigConstant configConstant;

    /**
     * @param userName
     * @param password
     * @author Anson
     * @date 17-3-24
     * @name 系统登陆
     * @since 1.0.2
     */
    @RequestMapping("/login")
    public JsonBack<SystemUserVo> managerLogin(HttpServletRequest request, @RequestParam("userName") String userName,
                                               @RequestParam("password") String password) {
        JsonBack<SystemUserVo> back = null;
        try {
            if (userName == null || userName.isEmpty()
                    || password == null || password.isEmpty()) {
                throw new BusinessException(PARAM_ILLEGAL_ERROR.getCodeStatus());
            } else {
                String ip = request.getRemoteAddr();
                SystemUserVo vo = this.service.login(userName, password, ip);
                if (vo != null) {
                    long sessionTimeout = configConstant.getSessionTimeOut();
                    UserSession session = UserSession.instance(vo, sessionTimeout);
                    WebUtils.setSessionAttribute(request, ADMIN_SESSION_KEY, session.toJson());
                    back = JsonBack.success(vo);
                } else {
                    back = JsonBack.error(MANAGER_LOGIN_PASSWORD_ERROR);
                }
            }
        } catch (BusinessException e) {
            back = JsonBack.error(e);
            LOGGER.error("管理员登陆异常", e);
        } catch (Exception e) {
            back = JsonBack.error(SYSTEM_CODE_ERROR);
            LOGGER.error("管理员登陆异常", e);
        }
        return back;
    }


    /**
     * @author Anson
     * @date 17-3-24
     * @name 系统退出
     * @since 1.0.2
     */
    @RequestMapping("/logout")
    public JsonBack<Boolean> managerLogout(HttpServletRequest request) {
        JsonBack<Boolean> back = null;
        try {
            Object adminSession = WebUtils.getSessionAttribute(request,
                    ADMIN_SESSION_KEY);
            Boolean isLogout = true;
            if (adminSession != null) {
                UserSession userSession = UserSession.jsonToBean(adminSession.toString());
                isLogout = this.service.logout(userSession.getUserName());
            }
            if (isLogout) {
                WebUtils.setSessionAttribute(request, ADMIN_SESSION_KEY, null);
            }
            back = JsonBack.success(isLogout);
        } catch (BusinessException e) {
            back = JsonBack.error(e);
            LOGGER.error("管理员退出异常", e);
        } catch (Exception e) {
            back = JsonBack.error(SYSTEM_CODE_ERROR);
            LOGGER.error("管理员退出异常", e);
        }
        return back;
    }

    /**
     * @param request
     * @param password 密码
     * @author Anson
     * @date 17-4-17
     * @name 修改密码
     * @since 1.0.4
     */
    @RequestMapping("/changePasswd")
    public JsonBack<Boolean> changepasswd(HttpServletRequest request,@RequestParam("passwordOld") String passwordOld,
                                          @RequestParam("password") String password) {
        JsonBack<Boolean> back = null;
        try {
            Object adminSession = WebUtils.getSessionAttribute(request,
                    ADMIN_SESSION_KEY);
            boolean isSuccess = false;
            if (adminSession != null) {
                UserSession userSession = UserSession.jsonToBean(adminSession.toString());
                isSuccess = this.service.changepasswd(userSession.getUserId(), userSession.getUserName(), password,passwordOld);
            }
            back = JsonBack.success(isSuccess);
        } catch (BusinessException e) {
            back = JsonBack.error(e);
            LOGGER.error("修改密码异常", e);
        } catch (Exception e) {
            back = JsonBack.error(SYSTEM_CODE_ERROR);
            LOGGER.error("修改密码异常", e);
        }
        return back;
    }
}
